package com.eip.zd.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eip.zd.entity.Cust;
import com.eip.zd.entity.Pay;
import com.eip.zd.entity.Project;
import com.eip.zd.mapper.PayMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class PayService {
    @Resource
    private PayMapper payMapper;
    @Resource
    private CustService custService;
    @Resource
    private ProjectService projectService;

    public List<Pay> getPayList(String keyword) {
        List<Pay> payList = payMapper.getPayList(keyword);
        List<Cust> custList = custService.getCustList(null);
        List<Project> projectList = projectService.getProjectList1(null);

        payList.stream().forEach(pay -> {
            String custId = pay.getCustId();
            Long projectId = pay.getProjectId();
            Cust cust = custList.stream().filter(c -> c.getCustId().equals(custId)).findFirst().orElse(null);
            Project project = projectList.stream().filter(p -> p.getId().equals(projectId)).findFirst().orElse(null);
            pay.setCustName(cust.getName());
            pay.setProjectName(project.getProjectName());
        });
        return payList;
    }

    public void add(Pay pay) {
        String format = DateUtil.format(new Date(), "yyMMdd");
        QueryWrapper<Pay> wrapper = new QueryWrapper<>();
        wrapper.likeRight("pay_id", format);
        Integer count = payMapper.selectCount(wrapper);
        BigDecimal bigDecimal1 = BigDecimal.valueOf(count);
        BigDecimal bigDecimal2 = new BigDecimal(format + "0000");
        pay.setPayId(bigDecimal1.add(bigDecimal2));
        if (StrUtil.hasEmpty(pay.getPayDate())) {
            pay.setPayDate(DateUtil.format(new Date(), "yyyy-MM-dd"));
        }
        payMapper.insert(pay);
    }

    public void update(Pay pay) {
        payMapper.updateById(pay);
    }

    public void remove(Long id) {
        payMapper.deleteById(id);
    }

    public void ifUse(Long id) {
        Pay pay = payMapper.selectById(id);
        if (pay.getIfUse() == 1) {
            pay.setIfUse(2);
        } else {
            pay.setIfUse(1);
        }
        payMapper.updateById(pay);
    }
}
